import Axios from 'axios'

const dataCode = {
  success: 0,
  login: [6005001000001, 7001002000008]
}

const URL_PREFIX = 'http://public-tjpm-bistudio4-core-server.k8s1.internal.weimobqa.com'

export const REDIRECT_URL = `${encodeURIComponent(window.location.href)}`

export const LOGIN_REDIRECT_URL = `${URL_PREFIX}/login/ldap/login?redirectUrl=${REDIRECT_URL}`

const baseURL = `${URL_PREFIX}/api`

const axios = Axios.create({
  baseURL,
  timeout: 10000
})

axios.interceptors.request.use(
  (config) => ({
    ...config,
    headers: {
      Accept: "application/json;charset=UTF-8",
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*",
      'x-janus-random': 12345678,
      'x-janus-timestamp': 1234567890,
      'x-janus-signature': '8699863b4e3da2b28e6e9bd2c1c9b0416aafbb053d4471adeefa25ca49a75d6e',
      'x-janus-sso-username': 'gang.li04',
      'x-janus-sso-givenname': 'gang.li04',
      terraaccountid: '15823001600'
    },
    data: {
      dashboardId: '1696087152263280',
      districtId: '1379528330444805',
      ...config.data
    }
  }),
  (error) => {
    return Promise.reject(error)
  }
)

// 后置拦截器（获取到响应时的拦截）
axios.interceptors.response.use(
  (response) => {
    const { status, data } = response
    if (status === 200) {
      const { errcode, errmsg } = data
      if (dataCode.login.includes(errcode)) {
        window.location.href = LOGIN_REDIRECT_URL
      }
      if (errcode === 0) {
        return Promise.resolve(data.data)
      } else {
        return Promise.reject(errmsg)
      }
    }
    return Promise.reject(data)
  },
  (error) => {
    const { code, response } = error
    if (code === 'ECONNABORTED') {
      return Promise.reject('请求超时')
    }
    if (response) {
      const { data, status } = response
      if (status === 500) {
        return Promise.reject(data.message)
      } else if (data.code === 403) {
        return Promise.reject('对不起，您没有此页面的访问权限')
      } else if (data.code === 401) {
        window.location.href = `${data.data}${REDIRECT_URL}`
      } else {
        return Promise.reject(error || '系统错误')
      }
    }
    return Promise.reject('网络错误')
  }
)

export default axios
